#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

//    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));

    ui->lineEdit_3->setEnabled(false);

    /* 查找可用的串口 */
    find_seralport();

}

MainWindow::~MainWindow()
{
    delete ui;
}


/* 查找可用的串口 */
void MainWindow::find_seralport()
{

    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        QSerialPort serial;
        serial.setPort(info);
        if(serial.open(QIODevice::ReadWrite))
        {
            ui->PortBox->addItem(serial.portName());
            serial.close();
        }
    }
}

/* 打开串口 */
void MainWindow::on_openPortBtn_clicked()
{
    if(ui->PortBox->isEnabled())
    {
        ui->openPortBtn->setText("关闭");		//按下“OpenPort”后，按键显示为“ClosePort”
        ui->PortBox->setDisabled(true);	//按下“OpenPort”后，禁止再修改COM口
        serial.setPortName(ui->PortBox->currentText());	//设置COM口
        serial.setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections);//设置波特率和读写方向
        serial.setDataBits(QSerialPort::Data8);		//数据位为8位
        serial.setFlowControl(QSerialPort::NoFlowControl);//无流控制
        serial.setParity(QSerialPort::NoParity);	//无校验位
        serial.setStopBits(QSerialPort::OneStop);	//一位停止位
        serial.close();					//先关串口，再打开，可以保证串口不被其它函数占用。
        if(serial.open(QIODevice::ReadWrite))		//以可读写的方式打开串口
        {
            connect(&serial,SIGNAL(readyRead()),this,SLOT(read_Com()));	//把串口的readyRead()信号绑定到read_Com()这个槽函数上
        }
//        ui->sendButton->setEnabled(true);
    }
    else
    {
        ui->openPortBtn->setText("打开");		//按下“ClosePort”后，按键显示为“OpenPort”
        ui->PortBox->setEnabled(true);		//按下“ClosePort”后，COM口可被修改
        serial.close();					//关串口
        //关闭发送按钮的使能
//        ui->sendButton->setEnabled(false);
    }
}

/* 手动添加的槽函数声明,用于读出串口缓冲区的内容 */
void MainWindow::read_Com()
{
    QByteArray buf;
    /* 信号到来，读取所有的字符串 */
    buf = serial.readAll();

    /* 如果真的有数据 */
    if(!buf.isEmpty())
    {
        QString str = ui->recvTextBrowser->toPlainText();
        str+=tr(buf);
        ui->recvTextBrowser->clear();
        ui->recvTextBrowser->append(str);
    }

    /* 获取系统id */
    if(buf.indexOf(s7) >= 0)
    {
        qDebug() << buf.indexOf(s7);
        QString buffer = buf;
        qDebug() << buf;
        QString temp;
        buffer = buffer.mid(7 + buf.indexOf(s7));
        temp = buffer.left(5);
        sys_id = temp.toInt(0,10);
        qDebug() << temp;


        ui->spinBox->setValue(sys_id / 256);
        ui->spinBox_2->setValue(sys_id % 256);
    }

    /* 获取MCU_ID */
    if(buf.indexOf(s) >= 0)
    {
        qDebug() << buf.indexOf(s);
        QString buffer = buf;
        qDebug() << buf;
        QString temp;
        buffer = buffer.mid(7 + buf.indexOf(s));
        for(int i = 0; i < 3; i++)
        {
            for(int j = 0; j < 4; j++)
            {
                temp = buffer.left(2);
                mcu[j + i * 4] = temp.toInt(0,16);
                buffer = buffer.mid(2);
                qDebug() << temp;
            }
        buffer = buffer.mid(1);
        }

        QByteArray a;   /* 转换成QByteArray是为了能够toHex() */
        a.resize(12);
        for(int i = 0; i < 12; i++)
        {
            a[i] = mcu[i];
        }

        QString b(a.toHex().toUpper());     /* 转换成字符串是为了能够插入空格 */

        b.insert(16,"-");
        b.insert(8,"-");


        ui->lineEdit_3->clear();
        ui->lineEdit_3->setText(b);


    }



    /* 获取LORA参数 */
    if(buf.indexOf(s2) >= 0)
    {
        qDebug() << buf.indexOf(s2);
        QString buffer = buf;
        qDebug() << buf;
        QString temp;
        buffer = buffer.mid(12 + buf.indexOf(s2));
        for(int i = 0; i < 5; i++)
        {

                temp = buffer.left(2);
                lora[i] = temp.toInt(0,16);
                buffer = buffer.mid(6);
                qDebug() << temp;
        }  

        QByteArray a;   /* 转换成QByteArray是为了能够toHex() */
        a.resize(5);
        for(int i = 0; i < 5; i++)
        {
            a[i] = lora[i];
        }

        QString b(a.toHex().toUpper());     /* 转换成字符串是为了能够插入空格 */
        for(int i = 5 - 1; i > 0; i--)
        {
            b.insert(i * 2," ");
        }

        ui->lineEdit->clear();
        ui->lineEdit->setText(b);
    }


    /* 获取网关地址*/
    if(buf.indexOf(s8) >= 0)
    {
        qDebug() << buf.indexOf(s8);
        QString buffer = buf;
        qDebug() << buf;
        QString temp;
        buffer = buffer.mid(8 + buf.indexOf(s8));
        for(int i = 0; i < 2; i++)
        {

                temp = buffer.left(2);
                gate[i] = temp.toInt(0,16);
                buffer = buffer.mid(2);
                qDebug() << temp;
        }

        QByteArray a;   /* 转换成QByteArray是为了能够toHex() */
        a.resize(2);
        for(int i = 0; i < 2; i++)
        {
            a[i] = gate[i];
        }

        QString b(a.toHex().toUpper());     /* 转换成字符串是为了能够插入空格 */
        for(int i = 2 - 1; i > 0; i--)
        {
            b.insert(i * 2," ");
        }

        ui->lineEdit_2->clear();
        ui->lineEdit_2->setText(b);
    }

    /* 获取网关信道*/
    if(buf.indexOf(s9) >= 0)
    {
        qDebug() << buf.indexOf(s9);
        QString buffer = buf;
        qDebug() << buf;
        QString temp;
        buffer = buffer.mid(8 + buf.indexOf(s9));


        temp = buffer.left(2);
        gate[2] = temp.toInt(0,16);
        buffer = buffer.mid(2);
        qDebug() << temp;


        QByteArray a;   /* 转换成QByteArray是为了能够toHex() */
        a.resize(1);

        a[0] = gate[2];


        QString b(a.toHex().toUpper());     /* 转换成字符串是为了能够插入空格 */

        b.insert(0," ");


        QString str = ui->lineEdit_2->text();
        str += b;
        ui->lineEdit_2->setText(str);
    }

    /* 获取电流比 */
    if(buf.indexOf(s4) >= 0)
    {
        qDebug() << buf.indexOf(s4);
        QString buffer = buf;
        qDebug() << buf;
        QString temp;
        buffer = buffer.mid(14 + buf.indexOf(s4));
        temp = buffer.left(3);
        run[0] = temp.toInt(0,10);
        qDebug() << temp;
    }

    /* 获取功率 */
    if(buf.indexOf(s5) >= 0)
    {
        qDebug() << buf.indexOf(s5);
        QString buffer = buf;
        qDebug() << buf;
        QString temp;
        buffer = buffer.mid(11 + buf.indexOf(s5));
        temp = buffer.left(5);
        run[1] = temp.toInt(0,10);
        qDebug() << temp;
    }

    /* 获取间隙时间 */
    if(buf.indexOf(s6) >= 0)
    {
        qDebug() << buf.indexOf(s6);
        QString buffer = buf;
        qDebug() << buf;
        QString temp;
        buffer = buffer.mid(14 + buf.indexOf(s6));
        temp = buffer.left(5);
        run[2] = temp.toInt(0,10);
        qDebug() << temp;
    }

    /* 获取回路数 */
    if(buf.indexOf(s3) >= 0)
    {
        qDebug() << buf.indexOf(s3);
        QString buffer = buf;
        qDebug() << buf;
        QString temp;
        buffer = buffer.mid(13 + buf.indexOf(s3));
        temp = buffer.left(3);
        run[3] = temp.toInt(0,10);
        qDebug() << temp;


        /* 显示运行参数 */
        ui->spinBox_3->setValue(run[0]);
        ui->spinBox_4->setValue(run[1]);
        ui->spinBox_6->setValue(run[2]);
        ui->spinBox_7->setValue(run[3]);
    }



    buf.clear();
}



/* 设置ID */
void MainWindow::on_pushButton_4_clicked()
{
//    /* 获取CPU_ID */
//    char buf1[10] = {0xEA, 0xEB, 0xEE, 0x04, 0x00, GET_MCU, 0x00, 0x01, 0x0D, 0x0A};
//    serial.writeData(buf1, 10);
//    /* 显示 */
//    user_display(buf1, 10);


    char buf2[22] = {0xEA, 0xEB, 0xEE, 0x10, 0x00, SET_ID, mcu[0], mcu[1], mcu[2], mcu[3], mcu[4], mcu[5], mcu[6], mcu[7], mcu[8], mcu[9], mcu[10], mcu[11], 0x00, 0x01, 0x0D, 0x0A};
    buf2[18] = ui->spinBox->text().toInt();
    buf2[19] = ui->spinBox_2->text().toInt();
    serial.writeData(buf2, 22);
    /* 显示 */
    user_display(buf2, 22);
}



/* 16进制字符数组转字符串并显示 */
void MainWindow::user_display(char *s, int size)
{
    QByteArray a;   /* 转换成QByteArray是为了能够toHex() */
    a.resize(10);
    for(int i = 0; i < size; i++)
    {
        a[i] = s[i];
    }

    QString b(a.toHex().toUpper());     /* 转换成字符串是为了能够插入空格 */
    for(int i = size - 1; i >= 0; i--)
    {
        b.insert(i * 2," ");
    }
    ui->label_10->clear();
    ui->label_10->setText("成功发送 " + b);
}

void MainWindow::on_pushButton_clicked()
{
    /* 获取LORA参数*/
    char buf1[10] = {0xEA, 0xEB, 0xEE, 0x04, 0x00, GET_CTRL_LORA_PARAM, 0x00, 0x00, 0x0D, 0x0A};
    buf1[6] = ui->spinBox->text().toInt();
    buf1[7] = ui->spinBox_2->text().toInt();
    serial.writeData(buf1, 10);
    /* 显示 */
    user_display(buf1, 10);


}

void MainWindow::on_pushButton_8_clicked()
{
    /* 设置LORA参数*//* 备注：程序中最好用C0 */
    char buf1[18] = {0xEA, 0xEB, 0xEE, 0x0c, 0x00, SET_CTRL_LORA_DATA, 0x00, 0x01, 0x30, 0x01, 0x1a, 0x17, 0xc0, 0x00, 0x00, 0x00, 0x0D, 0x0A};
    buf1[6] = ui->spinBox->text().toInt();
    buf1[7] = ui->spinBox_2->text().toInt();
    /* 提取LORA参数 */
    QString lora_str(ui->lineEdit->text());
    QString temp;
    for(int i = 0; i < 4; i++)
    {

            temp = lora_str.left(2);
            buf1[8 + i] = temp.toInt(0,16);
            lora_str = lora_str.mid(3);
            qDebug() << temp;
    }
    /* 提取网关地址信道 */
    QString gate_str(ui->lineEdit_2->text());
    QString temp2;
    for(int i = 0; i < 3; i++)
    {
        temp2 = gate_str.left(2);
        buf1[13 + i] = temp2.toInt(0,16);
        gate_str = gate_str.mid(3);
        qDebug() << temp2;
    }

//    qDebug() << lora_str;
    serial.writeData(buf1, 18);
    /* 显示 */
    user_display(buf1, 18);
}

/* 清空显示 */
void MainWindow::on_pushButton_6_clicked()
{
    ui->recvTextBrowser->clear();
}

/* CPU_ID开灯 */
void MainWindow::on_pushButton_3_clicked()
{
    /* CPU_ID开灯 */
    char buf2[20] = {0xEA, 0xEB, 0xEE, 0x0e, 0x00, OP_MCU_OPEN, mcu[0], mcu[1], mcu[2], mcu[3], mcu[4], mcu[5], mcu[6], mcu[7], mcu[8], mcu[9], mcu[10], mcu[11], 0x0D, 0x0A};
    serial.writeData(buf2, 20);
    /* 显示 */
    user_display(buf2, 20);
}

/* CPU_ID关灯 */
void MainWindow::on_pushButton_5_clicked()
{
    /* CPU_ID关灯 */
    char buf2[20] = {0xEA, 0xEB, 0xEE, 0x0e, 0x00, OP_MCU_CLOSE, mcu[0], mcu[1], mcu[2], mcu[3], mcu[4], mcu[5], mcu[6], mcu[7], mcu[8], mcu[9], mcu[10], mcu[11], 0x0D, 0x0A};
    serial.writeData(buf2, 20);
    /* 显示 */
    user_display(buf2, 20);
}

/* 重启控制器*/
void MainWindow::on_pushButton_7_clicked()
{
    /* 重启控制器*/
    char buf1[10] = {0xEA, 0xEB, 0xEE, 0x04, 0x00, SET_CTRL_REBOOT, 0x00, 0x01, 0x0D, 0x0A};
    buf1[6] = ui->spinBox->text().toInt();
    buf1[7] = ui->spinBox_2->text().toInt();
    serial.writeData(buf1, 10);
    /* 显示 */
    user_display(buf1, 10);
}

/* 获取运行参数 */
void MainWindow::on_pushButton_9_clicked()
{
    /* 获取运行参数*/
    char buf1[10] = {0xEA, 0xEB, 0xEE, 0x04, 0x00, GET_RUN_PARAM, 0x00, 0x01, 0x0D, 0x0A};
    buf1[6] = ui->spinBox->text().toInt();
    buf1[7] = ui->spinBox_2->text().toInt();
    serial.writeData(buf1, 10);
    /* 显示 */
    user_display(buf1, 10);
}

void MainWindow::on_pushButton_2_clicked()
{
    /* 设置运行参数 */
    char buf2[16] = {0xEA, 0xEB, 0xEE, 0x0a, 0x00, SET_RUN_PARAM, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x0D, 0x0A};
    buf2[6] = ui->spinBox->text().toInt();
    buf2[7] = ui->spinBox_2->text().toInt();

    buf2[8] = ui->spinBox_3->text().toInt();
    buf2[9] = ui->spinBox_4->text().toInt() / 256;
    buf2[10] = ui->spinBox_4->text().toInt() % 256;
    buf2[11] = ui->spinBox_6->text().toInt() / 256;
    buf2[12] = ui->spinBox_6->text().toInt() % 256;
    buf2[13] = ui->spinBox_7->text().toInt();
    serial.writeData(buf2, 16);
    /* 显示 */
    user_display(buf2, 16);
}

void MainWindow::on_pushButton_10_clicked()
{
    /* 获取CPU_ID */
    char buf1[10] = {0xEA, 0xEB, 0xEE, 0x04, 0x00, GET_MCU, 0x00, 0x01, 0x0D, 0x0A};
    buf1[6] = ui->spinBox->text().toInt();
    buf1[7] = ui->spinBox_2->text().toInt();
    serial.writeData(buf1, 10);
    /* 显示 */
    user_display(buf1, 10);
}

/* 恢复出厂设置 */
void MainWindow::on_pushButton_11_clicked()
{
    /* 恢复出厂设置*/
    char buf1[10] = {0xEA, 0xEB, 0xEE, 0x04, 0x00, SET_CTRL_DEFAULT, 0x00, 0x01, 0x0D, 0x0A};
    buf1[6] = ui->spinBox->text().toInt();
    buf1[7] = ui->spinBox_2->text().toInt();
    serial.writeData(buf1, 10);
    /* 显示 */
    user_display(buf1, 10);
}


/* 时间结构体 */
typedef struct _time
{
    uint8_t year;
    uint8_t month;
    uint8_t day;
    uint8_t week;
    uint8_t hour;
    uint8_t minute;
    uint8_t second;
}TIME;

/* 十进制转BCD */
uint8_t DectoBCD(uint8_t dec)
{
    uint8_t hex;
    hex = dec / 10 * 16 + dec % 10;
    return hex;
}

/* 时间戳转时间 */
void timeStamptoTime(void *user_time, time_t *timer)
{
    struct tm *p;
    p = localtime(timer);

    ((TIME *)user_time)->year = DectoBCD(p->tm_year - 100);
    ((TIME *)user_time)->month = DectoBCD(p->tm_mon + 1);
    ((TIME *)user_time)->day = DectoBCD(p->tm_mday);
    ((TIME *)user_time)->week = DectoBCD(p->tm_wday);
    ((TIME *)user_time)->hour = DectoBCD(p->tm_hour);
    ((TIME *)user_time)->minute = DectoBCD(p->tm_min);
    ((TIME *)user_time)->second = DectoBCD(p->tm_sec);

    qDebug() << ((TIME *)user_time)->year;
    qDebug() << ((TIME *)user_time)->month;
    qDebug() << ((TIME *)user_time)->day;
    qDebug() << ((TIME *)user_time)->week;

    qDebug() << ((TIME *)user_time)->hour;
    qDebug() << ((TIME *)user_time)->minute;
    qDebug() << ((TIME *)user_time)->second;
}


void MainWindow::on_pushButton_22_clicked()
{
    /* 直接获取系统当前时间 */
//    QDateTime time1 = QDateTime::currentDateTime();//获取系统现在的时间
//    QString str1 = time1.toString("yyyy-MM-dd hh:mm:ss ddd"); //设置显示格式
//    ui->label_20->setText(str1);//在标签上显示时间

    /* 获取当前时间戳 */
    long int seconds = time((time_t*)NULL);
    qDebug() << seconds;
    QDateTime time = QDateTime::fromTime_t(seconds);

    TIME temp_time;
    timeStamptoTime(&temp_time, &seconds);

    /* 校时 */
    char buf[15] = {0xEA, 0xEB, 0xEE, 0x09, 0x00, SET_TIME, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x0A};

    buf[6] = temp_time.year;
    buf[7] = temp_time.month;
    buf[8] = temp_time.day;
    buf[9] = temp_time.week;

    buf[10] = temp_time.hour;
    buf[11] = temp_time.minute;
    buf[12] = temp_time.second;

    serial.writeData(buf, 15);
    /* 显示 */
    user_display(buf, 15);

    QString str = time.toString("yyyy-MM-dd hh:mm:ss ddd"); //设置显示格式
    ui->label_19->setText(str);//在标签上显示时间

}

/* 设置标准差阈值 */
void MainWindow::on_pushButton_12_clicked()
{
    char buf2[22] = {0xEA, 0xEB, 0xEE, 0x04, 0x00, 0x08, 0x00, 0x50, 0x0D, 0x0A};
    buf2[6] = ui->spinBox_8->text().toInt() / 256;
    buf2[7] = ui->spinBox_8->text().toInt() % 256;
    serial.writeData(buf2, 10);
    /* 显示 */
    user_display(buf2, 10);
}
